package org.bronycorps.mlptss.domain.controller;

import org.bronycorps.mlptss.domain.model.Player;
import org.bronycorps.mlptss.domain.model.Player.State;
import org.bronycorps.mlptss.manager.preferences.GameConfiguration;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Vector2;

public class PlayerHuman extends AbstractPlayerController {

	private Vector2 acceleration;
	private GameConfiguration gameConfiguration;
	private final String playerPrefix;

	public PlayerHuman(Player player) {
		super(player);

		this.playerPrefix = "player" + player.getIdPlayer();
		this.acceleration = player.getAcceleration();
		this.gameConfiguration = GameConfiguration.getInstance();
	}

	@Override
	public void act(float delta) {
		super.act(delta);

		switch (this.model.getState()) {
		case NORMAL:
		case WEAK:
		case INVINCIBLE:
			readInputs(delta);

			break;
		default:
			break;
		}

	}

	private void readInputs(float delta) {
		this.acceleration.x = (Gdx.input.isKeyPressed(this.gameConfiguration
				.getKeyMap(this.playerPrefix + ".left")) ? -this.model
				.getMaxSpeed() : (Gdx.input.isKeyPressed(this.gameConfiguration
				.getKeyMap(this.playerPrefix + ".right")) ? this.model
				.getMaxSpeed() : 0))
				* this.gameConfiguration.getInputSpeedScale();
		this.acceleration.y = (Gdx.input.isKeyPressed(this.gameConfiguration
				.getKeyMap(this.playerPrefix + ".up")) ? this.model
				.getMaxSpeed() : (Gdx.input.isKeyPressed(this.gameConfiguration
				.getKeyMap(this.playerPrefix + ".down")) ? -this.model
				.getMaxSpeed() : 0))
				* this.gameConfiguration.getInputSpeedScale();

		this.position.add(this.acceleration.x * delta, this.acceleration.y
				* delta);

		if (this.acceleration.len() > 0) {
			this.model.setAngle(this.acceleration.angle());
		} else {
			this.model.setAngle(0);
		}

		if (Gdx.input.isKeyPressed(this.gameConfiguration
				.getKeyMap(this.playerPrefix + ".shoot"))) {
			this.model.addSpecialAttackCharge(delta);
		} else if (this.model.getSpecialAttackCharge() > 0) {
			if (this.model.getSpecialAttackCharge() >= 1) {

				// if charge max, launch boss attack
				if (this.model.getSpecialAttackCharge() >= 3) {
					this.model.fireBossEvent();
				} else if (this.model.getSpecialAttackCharge() >= 2) {
					// or if charge at level 2, launch special missiles
					this.model.fireSpecialMissileEvent();
				}
				// in any case, fire special attack and reset maximum charge
				this.model.fireSpecialAttackEvent();
				this.model.setMaxSpecialAttackCharge(1);
			} else {
				this.model.fireShootEvent();
			}

			// finally reset charge
			this.model.setSpecialAttackCharge(0);
		}

		if (this.model.getState() != State.INVINCIBLE) {
			if (Gdx.input.isKeyPressed(this.gameConfiguration
					.getKeyMap(this.playerPrefix + ".bomb"))) {
				this.model.fireBombEvent();
			}
		}
	}

}
